const express = require("express");
const mysql = require("mysql");
const app = express();

app.use(express.json());
app.use(express.urlencoded({ extended: true }));
// 连接数据库
const db = mysql.createPool({
  host: "127.0.0.1",
  user: "root",
  password: "root",
  database: "nodetest",
});
// 修改
app.get("/posts", (req, res) => {
  db.query("select * from article where id=?", req.body.id, (err, result) => {
    if (err) {
      // 执行异常
      return res.send({ code: 9999, msg: err, data: null });
    } else if (result.length !== 0) {
      db.query(
        "update article set name=? where id=?",
        [req.body.name, req.body.id],
        (err, result) => {
          // console.log(result)
          if (err) return res.send({ code: 9999, msg: err }); // 操作异常
          if (result.affectedRows > 0) {
            // 文章更新成功
            return res.send({ code: 0, msg: "文章更新成功" });
          } else {
            // 文章更新失败
            return res.send({ code: 5000, msg: "文章更新失败" });
          }
        }
      );
    } else {
      res.send({ code: 5000, msg: "查无数据" });
    }
  });
});
// 增加
app.post("/posts", (req, res) => {
  // console.log(req.body.name)
  db.query(
    `insert into article values(null,'${req.body.name}')`,
    (err, result) => {
      if (err) return res.send({ code: 4444, msg: err });
      if (result.affectedRows > 0) {
        return res.send({ code: 0, msg: "创建成功" });
      } else {
        return res.send({ code: 444, msg: "创建失败" });
      }
    }
  );
});
// 删除
app.delete("/posts", (req, res) => {
  db.query("delete from article where id=?", req.body.id, (err, result) => {
    // console.log(result)
    if (err) return res.send({ code: 9999, msg: err }); // 操作异常
    if (result.affectedRows > 0) {
      // 删除文章成功
      return res.send({ code: 0, msg: "删除文章成功" });
    } else {
      // 删除文章失败
      return res.send({ code: 5000, msg: "删除文章失败" });
    }
  });
});
// 查询
app.put("/posts", (req, res) => {
  db.query(`select * from article`, (err, result) => {
    console.log(result);
    if (err) return res.send({ code: 4444, msg: err, data: null });
    res.send({ code: 0, msg: "读取成功" });
  });
});

app.listen(3000, "127.0.0.1", (err) => {
  console.log("服务器启动");
});
